require 'goldberg/user'

GoldbergFilters.module_eval do

  def goldberg_security_up_with_my_stuff
    logger.info "Running my own custom filters"
    authorised = true
    if(params[:controller] != nil && !params[:controller].empty?)
      begin
        object = Object.const_get(params[:controller].camelcase+'Controller').new
        #puts params[:controller].camelcase+'Controller'
        if(params[:action] == nil || params[:controller].empty?)
          action = 'index'
        else
          action = params[:action]
        end
        # Because this filter is loaded BEFORE Goldberg, we need to call Goldberg to load user data
        if Goldberg.settings
          Goldberg::AuthController.set_user(session)
        end
        authorised = object.do_authorise(action, params)

      rescue
      end
    end

    if authorised
      return goldberg_security_up_without_my_stuff
    else
      respond_to do |format|
        format.html do
          redirect_to Goldberg.settings.permission_denied_page.url
        end
        format.js do
          flash[:error] =  Goldberg.settings.permission_denied_page.content_html
          render :status => 400, :layout => 'ajax'
        end
        format.xml  do
          render :status => 400, :xml => error_xml(*ERROR_PERMISSION_DENIED)
        end
      end
    end
  end

  alias_method_chain :goldberg_security_up, :my_stuff

end